<template>
  <div>
    <el-drawer custom-class="drawer_box" :size="drawerShow.width" :title="drawerShow.title" v-model="drawerShow.visible" ref="DrawerRef">
      <el-tabs v-model="activeName" @tab-change="tabClick">
        <el-tab-pane label="未转化" :name="1"> </el-tab-pane>
        <el-tab-pane label="已转化" :name="2"> </el-tab-pane>
        <el-tab-pane label="已放弃" :name="3"> </el-tab-pane>
      </el-tabs>
      <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset"></ZwSearchForm>
      <ZwTable ref="tableRef" class="table-box" :option="tableOption" :fetch-params="state.searchParams" :fetch-api="getData()" @select="onSelect" @selection-change="onSelectionChange" @select-all="onSelectAll">
        <template #headerOperate>
          <el-button plain :disabled="!abandonForm.clue_list.length" v-show="activeName == 1" class="table-btn" @click="onConversionPer('BATCH')">批量转化</el-button>
          <el-button plain :disabled="!abandonForm.clue_list.length" v-show="activeName == 1" @click="onAbandon('BATCH')">批量放弃</el-button>
        </template>
      </ZwTable>
    </el-drawer>
  </div>

  <custDetail ref="custDetailRef"></custDetail>
  <!-- 放弃弹框 -->
  <Dialog :appDialog="abandonDialog">
    <div class="abandon">
      <div class="photo"><img src="@/assets/customer/warn.png" /></div>
      <div class="abandonstyle">
        <div style="margin-bottom: 16px">放弃线索后，线索将不能被员工认领、不能被公海分配和回收</div>
        <el-form :model="abandonForm" :rules="rules" ref="abandonFormRef" label-width="auto">
          <el-form-item label="放弃原因" prop="invalid_id">
            <el-select v-model="abandonForm.invalid_id" placeholder="请选择放弃原因">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in reasonListData" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Dialog>
  <ConvertCustomer ref="ConvertCustomerRef" @submit="reload" />
  <TransCustomer :open="isopenCustomer" :seas_id="seas_id" :title="title" :rowid="rowid" @close="isopenCustomer = false" @submit="reset"></TransCustomer>
  <NewClubCompany v-model="openCompany" ref="NewClubCompanyRef" :sourceArr="sourceArr" :seas_id="seas_id" :isEdit="isEdit" @close="closeNewClubCompany" @submit="submitData(true)"></NewClubCompany>
</template>
<script lang="tsx" setup>
import ConvertCustomer from './ConvertCustomer.vue'
import Dialog from '@/components/Dialog.vue'
import { reasonList } from '@/api/customer/clubManage/commonSea'
import { getClueConvList, getClueLevelList, taskClueAbandon, taskConversionPer, batchTaskConversionPer, taskConversion } from '@/api/employe/employeetasks/taskmanage'
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { dividerProps, ElButton, ElMessage, ElPopover, ElProgress } from 'element-plus'
import ZwSearchForm from '@/components/zw/search-form/SearchForm'
import ZwTable from '@/components/zw/table/Table'
import custDetail from './custDetail.vue'
import { deepCopy } from '@/utils/helper'
import { getSetionId } from '@/utils/utils'
import TransCustomer from './TransCustomer.vue'
import NewClubCompany from './NewClubCompany.vue'

const DrawerRef = ref(null)
const tableRef = ref(null)
const custDetailRef = ref(null)
const AddCustomerRef = ref()
const abandonFormRef = ref()
const checkList = ref([])
const activeName = ref(2)
const isopenCustomer = ref(false)
const openCompany = ref(false)
const sourceArr = reactive([])
const isEdit = ref()
const NewClubCompanyRef = ref(null)
let title = ref('') //流转记录抽屉标题
const seas_id = ref()
const rowid = ref(null) //行线索id
const emit = defineEmits(['update:modelValue', 'close', 'submit'])

const abandonForm = ref({
  invalid_id: '',
  clue_list: []
})
const rules = reactive({
  invalid_id: [{ required: true, message: '请选择放弃原因', trigger: 'blur' }]
})

const defaultParams = reactive({
  task_id: '',
  status: 2,
  level: '',
  call_result: '',
  work_user_ids: []
})
const callResult = reactive([
  {
    name: '全部',
    id: -1
  },
  {
    name: '--',
    id: 0
  },
  {
    name: '已接通',
    id: 1
  },
  {
    name: '未接通',
    id: 2
  },
  {
    name: '挂机',
    id: 3
  },
  {
    name: '空号',
    id: 4
  }
])
const state = reactive({
  searchParams: deepCopy(defaultParams)
})
const tasksRemind = (val: any) => {}
const searchOption = ref([
  {
    label: '线索等级',
    name: 'level',
    value: '',
    type: 'select',
    placeholder: '请选择线索等级',
    fetchOptionApi: () => {
      return new Promise((resolve) => {
        getClueLevelList().then((res: any) => {
          resolve(res.data)
        })
      })
    },
    formatOption: (v) => ({
      label: v.name,
      value: v.id
    })
  },

  {
    label: '执行员工',
    name: 'work_user_ids',
    value: [],
    type: 'select',
    placeholder: '请选择员工',
    multiple: true,
    popperClass: 'zw-hide_select_option',
    isUserSelect: true,
    formatOption: (v) => ({
      label: v.name,
      value: v.id
    })
  }
])

// 选中表格 checkbox
const onSelect = (selection: any, row: any) => {
  abandonForm.value.clue_list = getSetionId('cule_id', selection)
}
// 选择项变更
const onSelectionChange = (selection: any) => {}
// 全选
const onSelectAll = (selection: any) => {
  abandonForm.value.clue_list = getSetionId('cule_id', selection)
}

const tableOption = ref([
  {
    type: 'selection',
    width: 55,
    fixed: 'left'
  },
  {
    prop: 'phone',
    label: '手机号'
  },
  {
    prop: 'level',
    label: '线索等级'
    // width: 120
  },
  {
    prop: 'remark',
    label: '备注',
    width: 160,
    render({ row }) {
      return <p>{row.remark ? row.remark : '--'}</p>
    }
  },
  {
    prop: 'work_user',
    label: '执行人'
  }
])
const obj4 = {
  prop: 'operate',
  label: '操作',
  width: 180,
  fixed: 'right',
  isOperate: true,
  render({ row, column, index }) {
    return (
      <div>
        <ElButton
          class="sopBtn"
          size="small"
          disabled={activeName.value != 1}
          onClick={() => {
            onConversionPer('ONE', row)
          }}
        >
          转化为客户
        </ElButton>
        <ElButton
          class="sopBtn"
          size="small"
          disabled={activeName.value != 1}
          onClick={() => {
            onAbandon('ONE', row)
          }}
        >
          放弃
        </ElButton>
      </div>
    )
  }
}
// tan 切换
const tabClick = (pane: any, ev: any) => {
  const index = tableOption.value.findIndex((i: any) => i.label == '操作')
  if (activeName.value != 1 && index != -1) {
    tableOption.value.splice(index, 1)
  } else if (activeName.value == 1 && index == -1) {
    tableOption.value.splice(tableOption.value.length - 1, 0, obj4)
  }
}
const search = (v: any) => {
  state.searchParams = { ...state.searchParams, ...v }
}
const reset = (v?: any) => {
  state.searchParams = {
    ...state.searchParams,
    level: '',
    call_result: '',
    work_user_ids: []
  }
}
const reload = () => {
  tableRef.value.reload()
}
const cancelSecond = (type: number, text: string) => {
  if (!abandonFormRef.value) return
  abandonFormRef.value.resetFields()
  abandonDialog.visible = false
  ElMessage.success(text)
  if (type === 1) {
    abandonForm.value.clue_list = []
    reset()
  }
}
const closeNewClubCompany = (): void => {
  openCompany.value = false
  // emit('close')
  reset()
}
const submitData = (flag: boolean): void => {
  if (flag) {
    // openCompany.value = false
  } else {
    // openPerson.value = false
  }
  emit('submit')
  reset()
}

const submitAbandon = async () => {
  if (!abandonFormRef.value) return
  await abandonFormRef.value.validate((valid, fields) => {
    if (valid) {
      taskClueAbandon(abandonForm.value).then((res: any) => {
        cancelSecond(1, '放弃成功')
      })
      abandonDialog.visible = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 放弃
const onAbandon = (type: string, row?: any) => {
  switch (type) {
    case 'ONE':
      abandonDialog.title = '放弃'
      abandonForm.value.clue_list.push(row.cule_id)
      break
    case 'BATCH':
      abandonDialog.title = '批量放弃'
      break
  }
  abandonDialog.visible = true
}

// 转化
const onConversionPer = (type: any, row?: any) => {
  console.log(row, type, '静静')
  switch (type) {
    case 'ONE':
      console.log(row, "d'sa'ddsad啊")
      if (row.type == 2) {
        console.log('111111a')
        openCompany.value = true
        NewClubCompanyRef.value.drawerData.seas_id = row.cule_id
      } else {
        console.log('222222')
        isopenCustomer.value = true
        rowid.value = row.cule_id
      }
      break
    case 'BATCH':
      batchTaskConversionPer({ clue_ids: abandonForm.value.clue_list }).then((res: any) => {
        ElMessage.success(`成功${res.success_total}条，失败${res.fail_total}条。${res.msg}`)
        reset()
      })
      break
  }
  seas_id.value = row.cule_id
}
const abandonDialog = reactive({
  visible: false,
  title: '删除提醒',
  width: '500px',
  cancel: cancelSecond,
  submit: submitAbandon,
  cancelText: '取消',
  submitText: '确定'
})
const getData = () => {
  return getClueConvList
}
const drawerShow = reactive({
  title: '',
  visible: false,
  width: 1100
})
const obj = {
  label: '沟通结果',
  name: 'call_result',
  value: '',
  type: 'select',
  placeholder: '请选择沟通结果',
  fetchOptionApi: () => {
    return new Promise((resolve) => {
      resolve(callResult)
    })
  },
  formatOption: (v) => ({
    label: v.name,
    value: v.id
  })
}
const obj3 = {
  label: '沟通结果',
  prop: 'call_result'
}
const openCue = (v: any) => {
  if (v.type == 1 && searchOption.value.length == 2) {
    searchOption.value.splice(1, 0, obj)
    tableOption.value.splice(2, 0, obj3)
  } else if (searchOption.value.length == 3 && v.type != 1) {
    searchOption.value.splice(1, 1)
    tableOption.value.splice(2, 1)
  }
  const params = deepCopy(state.searchParams)
  drawerShow.title = `【${v.name}】线索转化`
  drawerShow.visible = true
  drawerShow.width = 1100
  state.searchParams.task_id = v.id
}
watch(activeName, (v: any) => {
  state.searchParams.status = v
})
//获取放弃原因列表
const reasonListData = ref([])
const getReasonList = () => {
  reasonList({ page: 1, page_size: 99 }).then((res) => {
    reasonListData.value = res.data
  })
}
onMounted(() => {
  getReasonList()
})
defineExpose({
  openCue
})
</script>
<style lang="scss" scoped>
.table-btn {
  margin-right: 10px;
}

.abandon {
  display: flex;
  padding: 33px 0;

  img {
    width: 36px;
    height: 36px;
  }

  .photo {
    display: flex;
    align-items: center;
    margin-right: 5px;
  }

  .abandonstyle {
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    :deep .el-form-item {
      margin-bottom: 0px;
    }
  }
}
</style>
